package com.hunan.api.catv.service.biz.member;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.hunan.api.catv.common.CacheKey;
import com.hunan.api.catv.common.CacheName;
import com.hunan.api.catv.common.Constants;
import com.hunan.api.catv.common.ConstantsMsg;
import com.hunan.api.catv.entity.ServiceResult;
import com.hunan.api.catv.entity.dto.MemberInviteRuleDto;
import com.hunan.api.catv.entity.dto.MemberTryWatchLiveRuleDto;
import com.hunan.api.catv.entity.enums.BindCardEnum;
import com.hunan.api.catv.entity.enums.LoginType;
import com.hunan.api.catv.entity.enums.SmsTypeEnum;
import com.hunan.api.catv.entity.po.*;
import com.hunan.api.catv.entity.vo.MemberVo;
import com.hunan.api.catv.entity.vo.SimpleExtenalMemberVo;
import com.hunan.api.catv.entity.vo.SimpleMemberVo;
import com.hunan.api.catv.entity.vo.SystemDictVo;
import com.hunan.api.catv.factory.LoginFactory;
import com.hunan.api.catv.mq.MqConstants;
import com.hunan.api.catv.service.ResultService;
import com.hunan.api.catv.service.biz.attention.AttentionRecordBiz;
import com.hunan.api.catv.service.biz.cache.CacheBiz;
import com.hunan.api.catv.service.biz.cps.CpsBiz;
import com.hunan.api.catv.service.biz.invite.MemberInviteBiz;
import com.hunan.api.catv.service.biz.mall.YouzanMallBiz;
import com.hunan.api.catv.service.biz.member.open.MemberOpenBiz;
import com.hunan.api.catv.service.biz.member.related.MemberAccountRelatedBiz;
import com.hunan.api.catv.service.biz.mq.MqBiz;
import com.hunan.api.catv.service.biz.smartfamily.SmartFamilyBiz;
import com.hunan.api.catv.service.biz.system.SystemDictBiz;
import com.hunan.api.catv.service.biz.tencent_cloud.cos.CosBiz;
import com.hunan.api.catv.service.biz.tencent_cloud.sms.SmsBiz;
import com.hunan.api.catv.service.biz.toupiao.TouPiaoBiz;
import com.hunan.api.catv.service.biz.wx.WxBiz;
import com.hunan.api.catv.service.impl.member.MemberService;
import com.hunan.api.catv.utils.ExportExcel;
import com.hunan.api.catv.utils.GsonUtils;
import com.hunan.api.catv.utils.RandomUtils;
import com.hunan.api.catv.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.net.URL;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@CacheConfig(cacheNames = CacheName.member)
public class MemberBiz extends ResultService {

    private static final String MEMBER_TRY_WATCH_RULE = "member_try_watch_rule";
    private static final Integer INVITER_PLATINUM_ISLAND_TYPE = 2;
    private static final Integer INVITER_PLATINUM_ISLAND_MEMBER_ASSETS_TYPE = 2;
    private static final Integer VISIT_PLATINUM_ISLAND_TYPE = 3;
    private static final Integer VISIT_PLATINUM_ISLAND_MEMBER_ASSETS_TYPE = 3;

    private static final Integer UN_LOGIN_STATUS = 0;
    private static final Integer NORMAL_STATUS = 1;
    @Autowired
    MemberService memberService;

    @Autowired
    LoginFactory loginFactory;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MemberBiz memberBiz;

    @Autowired
    MqBiz mqBiz;

    @Autowired
    SmsBiz smsBiz;

    @Autowired
    CosBiz cosBiz;

    @Autowired
    CacheBiz cacheBiz;

    @Autowired
    CpsBiz cpsBiz;

    @Autowired
    TouPiaoBiz touPiaoBiz;

    @Autowired
    WxBiz wxBiz;

    @Autowired
    private YouzanMallBiz youzanMallBiz;

    @Autowired
    private MemberOpenBiz memberOpenBiz;

    @Autowired
    MemberInviteBiz memberInviteBiz;

    @Autowired
    SystemDictBiz systemDictBiz;

    @Value("${file.excelPath}")
    private String path;

    @Autowired
    AttentionRecordBiz attentionRecordBiz;

    @Autowired
    MemberAccountRelatedBiz memberAccountRelatedBiz;

    @Autowired
    SmartFamilyBiz smartFamilyBiz;

    public ServiceResult login(Integer loginType, String id, String sms, String ip, String phone, String pushToken) {
        LoginService loginService = loginFactory.getLoginService(loginType);
        String jgLoginToken = getServletRequest().getParameter("jgLoginToken");
        ServiceResult loginResult = loginService.login(id, phone, sms, ip, pushToken, jgLoginToken);
        if (!loginResult.getStatus()) {
            return loginResult;
        }
        MemberVo memberVo = new MemberVo();
        if (!ObjectUtils.isEmpty(loginResult.getData())) {
            JsonObject memberJson = GsonUtils.fromJson(loginResult.getData().toString(), JsonObject.class);
            if (memberJson.get("isBind").getAsBoolean()) {
                return loginResult;
            }
            memberVo = GsonUtils.fromJson(memberJson.get("member").getAsString(), MemberVo.class);
        }
        updateToken(memberVo.getMemberId(), pushToken);
        SimpleMemberVo sMemberVo = new SimpleMemberVo();
        BeanUtils.copyProperties(memberVo, sMemberVo);
        sMemberVo.setMemberSign(memberInviteBiz.checkMemberSign(memberVo.getMemberId()));
        sMemberVo.setMemberWhite(memberInviteBiz.checkMemberWhitelist(memberVo.getMemberId()));
//        sMemberVo.setMemberInvite(true);
        sMemberVo.setMemberInvite(checkMemberInvite(memberVo.getMemberId()));
        sMemberVo.setMemberAttention(attentionRecordBiz.checkAttention(memberVo.getMemberId()));
        sMemberVo.setInviterPhone(memberInviteBiz.findInviterPhone(memberVo.getMemberId()));
        sMemberVo.setSmartCardCode(StringUtils.isBlank(memberVo.getSmartCardCode()) ? memberVo.getSmartCardCode() : memberAccountRelatedBiz.getAccountId(memberVo.getSmartCardCode()));
        sMemberVo.setUserNo(String.valueOf(memberVo.getMemberId() + 192008));
        if (memberVo.getRegTime() != null) {
            sMemberVo.setRegTime(memberVo.getRegTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
//        sMemberVo.setPhone(sMemberVo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        JsonObject result = new JsonObject();
        result.add("member", GsonUtils.fromJson(GsonUtils.toJson(sMemberVo), JsonObject.class));
        result.add("auth", buildToken(memberVo.getMemberId()));
        //result.add("yz", GsonUtils.fromJson(GsonUtils.toJson(youzanLoginResVo), JsonObject.class));
        log.info("用户" + memberVo.getMemberId() + "登陆。。");
        mqBiz.push(MqConstants.OPEN_APP_EVENT_EXCHANGE, MqConstants.OPEN_APP_EVENT_ROUTINGKEY, memberVo.getMemberId());
        return buildOK(result, "登录成功");
    }

    public ServiceResult logout(String token, String refreshToken) {
        String token_key = MessageFormat.format(CacheKey.memberToken, token);
        String refreshKey = MessageFormat.format(CacheKey.memberRefreshToken, refreshToken);
        redisUtils.del(token_key);
        redisUtils.del(refreshKey);
        return buildOK(true, ConstantsMsg.member_logout_success);
    }

    public JsonObject buildToken(Integer memberId) {
        JsonObject result = new JsonObject();
        StringBuilder builder = new StringBuilder();
        builder.append(memberId);
        builder.append(DateTime.now().getMillis());
        String token = DigestUtils.md5DigestAsHex(builder.toString().getBytes());
        String key = MessageFormat.format(CacheKey.memberToken, token);
        StringBuilder refreshBuilder = new StringBuilder();
        refreshBuilder.append(memberId);
        refreshBuilder.append(DateTime.now().getMillis());
        refreshBuilder.append(DateTime.now().getMillis());
        String refreshUUID = refreshBuilder.toString();
        String refreshToken = DigestUtils.md5DigestAsHex(refreshUUID.getBytes());
        String refreshKey = MessageFormat.format(CacheKey.memberRefreshToken, refreshToken);
        redisUtils.set(key, memberId, CacheKey.memberTokenExpireTime);
        redisUtils.set(refreshKey, memberId, CacheKey.memberRefreshTokenExpireTime);
        result.addProperty("smartFamilyToken", Optional.ofNullable(smartFamilyBiz.login(memberId)).orElse(""));
        result.addProperty("token", token);
        result.addProperty("expire", CacheKey.memberTokenExpireTime);
        result.addProperty("refreshToken", refreshToken);
        return result;
    }

    public ServiceResult refresh(String refreshToken) {
        String refreshKey = MessageFormat.format(CacheKey.memberRefreshToken, refreshToken);
        Object _refreshToken = redisUtils.get(refreshKey);
        if (ObjectUtils.isEmpty(_refreshToken)) {
            return buildFail("");
        }
        Integer memberId = Integer.valueOf(_refreshToken.toString());
        if (!memberId.equals(0)) {
            JsonObject tokenResult = buildToken(memberId);
            if (!ObjectUtils.isEmpty(tokenResult)) {
                redisUtils.del(refreshKey);
                return buildOK(tokenResult);
            }
        }
        return buildFail("");
    }

    public ServiceResult bind(String id, Integer loginType, Integer memberId) {
        LoginService loginService = loginFactory.getLoginService(loginType);
        ServiceResult bindResult = loginService.bind(id, loginType, memberId);
        return bindResult;
    }

    public MemberVo info(Integer memberId) {
        return memberService.getById(memberId);
    }

    @Cacheable(unless = "#result == null", cacheManager = "cacheManager30m")
    public MemberVo cacheInfo(Integer memberId) {
        return memberService.getById(memberId);
    }

    public SimpleMemberVo simpleInfo(Integer memberId) {
        MemberVo memberVo = memberService.getById(memberId);
        memberVo.setPhone(memberVo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        SimpleMemberVo simpleMemberVo = new SimpleMemberVo();
        BeanUtils.copyProperties(memberVo, simpleMemberVo);
        simpleMemberVo.setUserNo(String.valueOf(memberVo.getMemberId() + 192008));
        simpleMemberVo.setSmartCardCode(StringUtils.isBlank(memberVo.getSmartCardCode()) ? memberVo.getSmartCardCode() : memberAccountRelatedBiz.getAccountId(memberVo.getSmartCardCode()));
        return simpleMemberVo;
    }

    /**
     *
     * @param memberId
     * @param sensitive 手机号是否要脱敏
     * @return
     */
    public ServiceResult simple(Integer memberId, boolean sensitive) {
        if (!ObjectUtils.isEmpty(memberId)) {
            MemberVo memberVo = memberService.getById(memberId);
            if (!ObjectUtils.isEmpty(memberVo)) {
                if (sensitive) {
                    memberVo.setPhone(memberVo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                }
                SimpleMemberVo simpleMemberVo = new SimpleMemberVo();
                BeanUtils.copyProperties(memberVo, simpleMemberVo);
                boolean sign = memberInviteBiz.checkMemberSign(memberVo.getMemberId());
                simpleMemberVo.setMemberSign(sign);
                simpleMemberVo.setMemberWhite(memberInviteBiz.checkMemberWhitelist(memberVo.getMemberId()));
                simpleMemberVo.setInviterPhone(sign ? memberInviteBiz.findInviterPhone(memberVo.getMemberId()) : "");
//                simpleMemberVo.setMemberInvite(true);
                simpleMemberVo.setMemberInvite(checkMemberInvite(memberVo.getMemberId()));
                simpleMemberVo.setMemberAttention(attentionRecordBiz.checkAttention(memberVo.getMemberId()));
                simpleMemberVo.setSmartCardCode(StringUtils.isBlank(memberVo.getSmartCardCode()) ? memberVo.getSmartCardCode() : memberAccountRelatedBiz.getAccountId(memberVo.getSmartCardCode()));
                simpleMemberVo.setUserNo(String.valueOf(memberVo.getMemberId() + 192008));
                if (memberVo.getRegTime() != null) {
                    simpleMemberVo.setRegTime(memberVo.getRegTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                return buildOK(simpleMemberVo);
            }
        }
        return buildFail(ConstantsMsg.member_simpleInfo_fail);
    }

    public void updateToken(Integer memberId, String pushToken) {
        JsonObject msg = new JsonObject();
        msg.addProperty("type", "push");
        msg.addProperty("memberId", memberId);
        msg.addProperty("pushToken", pushToken);
        mqBiz.push(MqConstants.member_conf_exchange, MqConstants.member_conf_routingkey, GsonUtils.toJson(msg));
    }

    public ServiceResult edit(Integer memberId, String pushToken) {
        Member member = new Member();
        member.setMemberId(memberId);
        MemberVo info = info(memberId);
        if (info != null) {
            Date firstLoginTime = info.getFirstLoginTime();
            if (StringUtils.isBlank(DateUtil.formatDateTime(info.getLastLoginTime()))) {
                firstLoginTime = new Date();
            }
            member.setFirstLoginTime(firstLoginTime);
        }
        member.setPushToken(pushToken);
        member.setLastLoginTime(new Date());
        return memberService.update(member);
    }

    public PageInfo<MemberVo> page(int pageNum, int pageSize, Integer memberId, Integer state) {
        PageHelper.startPage(pageNum, pageSize);
        Member member = new Member();
        member.setMemberId(memberId);
        member.setState(state);
        List<MemberVo> list = memberService.list(member);
        return new PageInfo<MemberVo>(list);
    }

    public ServiceResult update(Member member) {
        ServiceResult update = memberService.update(member);
        if (update.getStatus()) {
            //清除短视频缓存
            mqBiz.push(MqConstants.CLEAR_NEWS_INFO_EXCHANGE, MqConstants.CLEAR_NEWS_INFO_ROUTINGKEY, member.getMemberId());
            redisUtils.delObjectCacheListPattern(CacheName.comment + "::page" + "*" + "." + member.getMemberId());
        }
        return update;
    }


    public ServiceResult update(Integer memberId, MultipartFile headImg, String nickName) {
        Member member = new Member();
        member.setMemberId(memberId);
        member.setNickName(nickName);
        if (headImg != null) {
            ServiceResult uploadResult = cosBiz.upload(1, headImg);
            if (!uploadResult.getStatus()) {
                return uploadResult;
            }
            JsonObject fileInfo = GsonUtils.fromJson(uploadResult.getData().toString(), JsonObject.class);
            if (!ObjectUtils.isEmpty(fileInfo)) {
                member.setAvatarUrl(fileInfo.get("url").getAsString());
            }
        }
        ServiceResult updateResult = memberService.update(member);
        if (updateResult.getStatus()) {
            //清除短视频缓存
            mqBiz.push(MqConstants.CLEAR_NEWS_INFO_EXCHANGE, MqConstants.CLEAR_NEWS_INFO_ROUTINGKEY, memberId);
            redisUtils.delObjectCacheListPattern(CacheName.comment + "::page" + "*" + "." + memberId);
            return buildOK(true, ConstantsMsg.member_update_success);
        }
        return buildFail(false, ConstantsMsg.member_update_fail);
    }

    public MemberVo getByPhone(String phone) {
        Member member = new Member();
        member.setPhone(phone);
        return memberService.get(member);
    }

    public MemberVo infoById(Integer loginType, String id) {
        Member member = new Member();
        if (loginType.equals(LoginType.wechat.getCode())) {
            member.setWxOpenid(id);
        }
        if (loginType.equals(LoginType.apple.getCode())) {
            member.setAppleId(id);
        }
        return memberService.get(member);
    }

    public ServiceResult checkPhoneId(Integer loginType, String phone, String id) {
        MemberVo memberVo = memberBiz.getByPhone(phone);
        if (!ObjectUtils.isEmpty(memberVo)) {
            if (loginType.equals(LoginType.sms.getCode())) {
                return buildFail(false, ConstantsMsg.phone_hasBound);
            }
            if (loginType.equals(LoginType.wechat.getCode())) {
                String wxOpenid = memberVo.getWxOpenid();
                if (!ObjectUtils.isEmpty(wxOpenid) && !id.equals(wxOpenid)) {
                    return buildFail(false, ConstantsMsg.phone_hasBound);
                }
            }
            if (loginType.equals(LoginType.apple.getCode())) {
                String appleUserInfoKey = MessageFormat.format(CacheKey.member_appleUserInfo, id);
                String sub = redisUtils.get(appleUserInfoKey).toString();
                String appId = memberVo.getAppleId();
                if (!ObjectUtils.isEmpty(appId) && !sub.equals(appId)) {
                    return buildFail(false, ConstantsMsg.phone_hasBound);
                }
            }
        }
        return buildOK(true, "");
    }

    public ServiceResult updateId(Integer loginType, Integer memberId, String id, String avatarUrl, String nickName) {
        Member member = new Member();
        member.setMemberId(memberId);
        member.setLastLoginTime(new Date());
        MemberVo info = info(memberId);
        if (info != null) {
            Date firstLoginTime = info.getFirstLoginTime();
            if (StringUtils.isBlank(DateUtil.formatDateTime(info.getLastLoginTime()))) {
                firstLoginTime = new Date();
            }
            member.setFirstLoginTime(firstLoginTime);
        }
        if (loginType.equals(LoginType.wechat.getCode())) {
            String wxUserInfoKey = MessageFormat.format(CacheKey.member_wxUserInfo, id);
            JsonObject userInfo = GsonUtils.fromJson(redisUtils.get(wxUserInfoKey).toString(), JsonObject.class);
            String openid = userInfo.get("openid").getAsString();
            member.setWxOpenid(openid);
            member.setWxUnionid(userInfo.get("unionid").getAsString());
            member.setGender(userInfo.get("sex").getAsInt());
            member.setProvince(userInfo.get("province").getAsString());
            member.setCity(userInfo.get("city").getAsString());
            member.setCountry(userInfo.get("country").getAsString());
            String headimgurl = userInfo.get("headimgurl").getAsString();
            try {
                URL url = new URL(headimgurl);
                String http = url.toURI().getScheme();
                if ("http".equals(http)) {
                    headimgurl.replace("http", "https");
                }
            } catch (Exception e) {
                log.error("{}", e);
            }
            log.info("[headimgurl:{}]", headimgurl);
            member.setAvatarUrl(headimgurl);
            member.setNickName(userInfo.get("nickname").getAsString());
        }
        if (loginType.equals(LoginType.apple.getCode())) {
            String appleUserInfoKey = MessageFormat.format(CacheKey.member_appleUserInfo, id);
            String sub = redisUtils.get(appleUserInfoKey).toString();
            member.setAppleId(sub);
        }
        ServiceResult update = memberBiz.update(member);
        if (!update.getStatus()) {
            return buildFail(false, ConstantsMsg.bindPhone_fail);
        }
        return buildOK(true, "");
    }

    public ServiceResult register(Integer loginType, String id, String phone, String nickName, Integer gender, String avatarUrl, String ip, String pushToken) {
        Member member = new Member();
        member.setRegIp(ip);
        member.setPhone(phone);
        member.setIdentifier(DigestUtils.md5DigestAsHex((phone + "WNAPP").getBytes()));
        member.setPushToken(pushToken);
        if (loginType.equals(LoginType.wechat.getCode())) {
            String wxUserInfoKey = MessageFormat.format(CacheKey.member_wxUserInfo, id);
            JsonObject userInfo = GsonUtils.fromJson(redisUtils.get(wxUserInfoKey).toString(), JsonObject.class);
            member.setWxOpenid(userInfo.get("openid").getAsString());
            member.setWxUnionid(userInfo.get("unionid").getAsString());
            member.setGender(userInfo.get("sex").getAsInt());
            member.setNickName(userInfo.get("nickname").getAsString());
            String headimgurl = userInfo.get("headimgurl").getAsString();
            try {
                URL url = new URL(headimgurl);
                String http = url.toURI().getScheme();
                if ("http".equals(http)) {
                    headimgurl.replace("http", "https");
                }
            } catch (Exception e) {
                log.error("{}", e);
            }
            log.info("[headimgurl:{}]", headimgurl);
            member.setAvatarUrl(headimgurl);
            member.setCountry(userInfo.get("country").getAsString());
            member.setCity(userInfo.get("city").getAsString());
            member.setProvince(userInfo.get("province").getAsString());
        }
        if (loginType.equals(LoginType.sms.getCode())) {
            member.setAvatarUrl(cacheBiz.getSystemDict(Constants.default_headImg));
            member.setNickName("WN" + RandomUtils.getRandom(4) + phone.substring(phone.length() - 4));
        }
        if (loginType.equals(LoginType.apple.getCode())) {
            member.setAvatarUrl(cacheBiz.getSystemDict(Constants.default_headImg));
            member.setNickName("WN" + RandomUtils.getRandom(4) + phone.substring(phone.length() - 4));
            String appleUserInfoKey = MessageFormat.format(CacheKey.member_appleUserInfo, id);
            String sub = redisUtils.get(appleUserInfoKey).toString();
            member.setAppleId(sub);
        }
        if (loginType.equals(LoginType.jiguang.getCode())) {
            member.setAvatarUrl(cacheBiz.getSystemDict(Constants.default_headImg));
            member.setNickName("WN" + RandomUtils.getRandom(4) + phone.substring(phone.length() - 4));
        }
        ServiceResult addResult = memberService.add(member);
        if (addResult.getStatus()) {
            JsonObject msg = new JsonObject();
            msg.addProperty("type", "im");
            msg.addProperty("memberId", member.getMemberId());
            mqBiz.push(MqConstants.member_conf_exchange, MqConstants.member_conf_routingkey, GsonUtils.toJson(msg));

            MemberTryWatchLiveRuleDto memberTryWatchRuleDto = JSONUtil.toBean(systemDictBiz.getStringByKey(MEMBER_TRY_WATCH_RULE), MemberTryWatchLiveRuleDto.class);
            if (memberTryWatchRuleDto != null) {
                Boolean globalTryWatchSwitch = Boolean.valueOf(Optional.ofNullable(memberTryWatchRuleDto.getGlobalTryWatchSwitch()).orElse("false"));
                if (globalTryWatchSwitch) {
                    mqBiz.push(MqConstants.MEMBER_TRY_WATCH_LIVE_EXCHANGE, MqConstants.MEMBER_TRY_WATCH_LIVE_ROUTINGKEY, GsonUtils.toJson(phone));
                }
            }
            return buildOK(member.getMemberId(), "");
        }
        return buildFail(false, ConstantsMsg.member_login_fail);
    }

    public ServiceResult boundPhone(Integer loginType, String id, String phone) {
        MemberVo memberVo = memberBiz.getByPhone(phone);
        ServiceResult result = new ServiceResult();
        if (ObjectUtils.isEmpty(memberVo)) {
            result = memberBiz.register(loginType, id, phone, null, null, null, null, null);
            if (!result.getStatus()) {
                return result;
            }
        } else {
            if (0 != memberVo.getInviter() && 1 == memberVo.getInviteesStatus()) {
                Member member = new Member();
                member.setInviteesStatus(2);
                member.setMemberId(memberVo.getMemberId());
                member.setLastLoginTime(new Date());
                member.setFirstLoginTime(StringUtils.isBlank(DateUtil.formatDateTime(memberVo.getLastLoginTime())) ? new Date() : memberVo.getFirstLoginTime());
                ServiceResult updateResult = memberService.update(member);
                if (!updateResult.getStatus()) {
                    return updateResult;
                }
                touPiaoBiz.addTicketToUser(memberVo.getInviter(), 2);
            }
            result = memberBiz.updateId(loginType, memberVo.getMemberId(), id, memberVo.getAvatarUrl(), memberVo.getNickName());
            if (!result.getStatus()) {
                return result;
            }
        }
        return result;
    }

    /**
     * 转换Mac账号格式
     */
    private String convertMacCode(String smartCardCode) {
        smartCardCode = smartCardCode.indexOf("-") > 0 ? smartCardCode.replaceAll("-", ":") : smartCardCode;
        if (smartCardCode.length() == 12) {
            smartCardCode = smartCardCode.replaceAll("(.{2})", "$1:");
            smartCardCode = smartCardCode.substring(0, smartCardCode.length() - 1);
        }
        return smartCardCode;
    }

    /**
     * 绑卡失败返回不同错误提示
     */
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult bindCps(Integer memberId, String smartCardCode) {
        Map<String, Object> map = new HashMap<>(16);
        smartCardCode = convertMacCode(smartCardCode);
        map.put("smartCardCode", smartCardCode);
        map.put("resultType", BindCardEnum.INVALID.getCode());
        //ServiceResult cpsResult = cpsBiz.queryUserStatus(smartCardCode);
        ServiceResult cpsResult = cpsBiz.queryUserInfo(smartCardCode);
        if (!cpsResult.getStatus()) {
            return cpsResult;
        }
        MemberAccountRelated resultData = (MemberAccountRelated) cpsResult.getData();
        if (!(smartCardCode.equals(resultData.getMac()) || smartCardCode.equals(resultData.getAccountId()) || smartCardCode.equals(resultData.getCa()))) {
            return buildFail(map, ConstantsMsg.cps_user_invaid);
        }
        //查询该账号绑定上限
        Integer count = new MemberAccountRelated().selectCount(new QueryWrapper<MemberAccountRelated>().lambda()
                .eq(MemberAccountRelated::getAccountId, resultData.getAccountId())
                .eq(MemberAccountRelated::getStatus, 1)
                .eq(MemberAccountRelated::getType, 2));
        if (count >= 10) {
            map.put("resultType", BindCardEnum.BEYOND.getCode());
            return buildFail(map, ConstantsMsg.cps_bind_beyond);
        }
        MemberVo memberVo = memberService.getById(memberId);
        if (!ObjectUtils.isEmpty(memberVo)) {
            if (ObjectUtils.isEmpty(memberVo.getSmartCardCode())) {
                Member member = new Member();
                member.setMemberId(memberId);
                member.setSmartCardCode(smartCardCode.contains("HNTV") ? (StringUtils.isBlank(resultData.getCa()) ? resultData.getMac() : resultData.getCa()) : smartCardCode);
                member.setBindCa(1);
                ServiceResult updateResult = memberService.update(member);
                if (updateResult.getStatus()) {
                    //同步到大小屏绑定关系
                    boolean saveMemberAccountResult = saveMemberAccount(1, resultData, memberId);
                    log.info("同步到大小屏绑定关系:{},用户id:{},绑定结果:{}", smartCardCode, memberId, saveMemberAccountResult);
                    boolean insert = saveMemberBindRecord(1, memberId, smartCardCode);
                    log.info("用户绑定ca卡号:{},用户id:{},绑定结果:{}", smartCardCode, memberId, insert);
                    return buildOK(true, ConstantsMsg.cps_bind_success);
                }
            } else {
                map.put("resultType", BindCardEnum.BOUND.getCode());
                return buildFail(map, ConstantsMsg.cps_bind_already);
            }
        }
        return buildFail(map, ConstantsMsg.cps_bind_fail);
    }

    /**
     * 同步大小屏账号绑定
     */
    public boolean saveMemberAccount(Integer status, MemberAccountRelated resultData, Integer memberId) {
        boolean flag = false;
        //查询是否已存在
        MemberAccountRelated memberAccountRelated = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().eq(MemberAccountRelated.MEMBER_ID, memberId).eq(MemberAccountRelated.TYPE, 2));
        if (memberAccountRelated != null) {
            flag = resultData.setStatus(status).setId(memberAccountRelated.getId()).setUpdateTime(new Date()).updateById();
        } else {
            flag = resultData.setMemberId(memberId).setStatus(status).setCreateTime(new Date()).setUpdateTime(new Date()).setType(2).insert();
        }
        return flag;
    }

    /**
     * 添加用户绑卡行为记录
     */
    public boolean saveMemberBindRecord(Integer bindType, Integer memberId, String smartCardCode) {
        return new MemberBindRecord().setBindType(bindType).setBindCard(smartCardCode).setCreateTime(new Date()).setUpdateTime(new Date()).setMemberId(memberId).insert();
    }

    @Transactional(rollbackFor = Exception.class)
    public ServiceResult unbindCps(Integer memberId) {
        MemberVo memberVo = memberService.getById(memberId);
        if (!ObjectUtils.isEmpty(memberVo)) {
            String smartCardCode = memberVo.getSmartCardCode();
            if (!ObjectUtils.isEmpty(smartCardCode)) {
                Member member = new Member();
                member.setMemberId(memberId);
                member.setSmartCardCode("");
                member.setBindCa(0);
                ServiceResult updateResult = memberService.update(member);
                if (updateResult.getStatus()) {
                    ServiceResult cpsResult = cpsBiz.queryUserInfo(smartCardCode);
                    if (!cpsResult.getStatus()) {
                        throw new RuntimeException("卡异常");
                    }
                    MemberAccountRelated resultData = (MemberAccountRelated) cpsResult.getData();
                    boolean saveMemberAccountResult = saveMemberAccount(0, resultData, memberId);
                    log.info("同步到大小屏绑定关系:{},用户id:{},绑定结果:{}", smartCardCode, memberId, saveMemberAccountResult);
                    boolean insert = saveMemberBindRecord(0, memberId, smartCardCode);
                    log.info("用户解绑ca卡号:{},用户id:{},绑定结果:{}", smartCardCode, memberId, insert);
                    //解绑遥控器
                    mqBiz.push(MqConstants.UNTIE_REMOTE_EXCHANGE, MqConstants.UNTIE_REMOTE_ROUTINGKEY, memberVo.getPhone());
                    //解绑3.0账号token
                    JsonObject msg = new JsonObject();
                    msg.addProperty("memberId", memberId);
                    msg.addProperty("type", 0);
                    mqBiz.push(MqConstants.CA_BIND_CHANGE_EXCHANGE,MqConstants.CA_BIND_CHANGE_ROUTINGKEY, GsonUtils.toJson(msg));
                    return buildOK(true, ConstantsMsg.cps_unbind_success);
                }
            }
        }
        return buildFail(ConstantsMsg.cps_unbind_fail);
    }

    public PageInfo<MemberVo> adminList(Integer pageNum, Integer pageSize, String phone, Integer bindCa, Integer state, Long startTime, Long endTime, String nickName, Integer memberType) {
        PageHelper.startPage(pageNum, pageSize);
        Member member = new Member();
        member.setBindCa(bindCa);
        member.setState(state);
        member.setPhone(phone);
        member.setNickName(nickName);
        member.setMemberType(memberType);
        if (!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(endTime)) {
            member.setStartTime(new Timestamp(startTime));
            member.setEndTime(new Timestamp(endTime));
        }
        List<MemberVo> list = memberService.list(member);
        list.forEach(memberVo -> {
            String region = memberVo.getCountry() + memberVo.getProvince() + memberVo.getCity();
            memberVo.setRegion(region);
        });
        return new PageInfo<MemberVo>(list);
    }

    /**
     * 邀请注册
     */
    public ServiceResult inviterRegist(String ip, String pushToken, String phone, String sms, Integer inviter) {
        MemberVo memberVo = this.info(inviter - 192008);
        if (memberVo != null && phone.equals(memberVo.getPhone())) {
            //提示语不同
            return buildOK(true, ConstantsMsg.member_register_fails);
        }
        ServiceResult smsResult = smsBiz.checkSmsCode(SmsTypeEnum.INVIT.getCode(), phone, sms);
        if (!smsResult.status) {
            return smsResult;
        }
        ServiceResult chekResult = memberBiz.checkPhoneId(LoginType.sms.getCode(), phone, null);
        if (!chekResult.status) {
            //提示语不同
            return buildOK(true, ConstantsMsg.member_register_fail);
        }
        Member member = new Member();
        member.setRegIp(ip);
        member.setPushToken(pushToken);
        member.setPhone(phone);
        member.setInviter(inviter - 192008);
        member.setInviteesStatus(1);
        member.setAvatarUrl(cacheBiz.getSystemDict(Constants.default_headImg));
        member.setNickName("WN" + RandomUtils.getRandom(4) + phone.substring(phone.length() - 4));
        ServiceResult addResult = memberService.add(member);
        if (addResult.status) {
            MemberTryWatchLiveRuleDto memberTryWatchRuleDto = JSONUtil.toBean(systemDictBiz.getStringByKey(MEMBER_TRY_WATCH_RULE), MemberTryWatchLiveRuleDto.class);
            if (memberTryWatchRuleDto != null) {
                Boolean globalTryWatchSwitch = Boolean.valueOf(Optional.ofNullable(memberTryWatchRuleDto.getGlobalTryWatchSwitch()).orElse("false"));
                if (globalTryWatchSwitch) {
                    mqBiz.push(MqConstants.MEMBER_TRY_WATCH_LIVE_EXCHANGE, MqConstants.MEMBER_TRY_WATCH_LIVE_ROUTINGKEY, GsonUtils.toJson(phone));
                }
            }
            return buildOK(true, ConstantsMsg.member_register_success);
        }
        return buildFail(false, ConstantsMsg.member_register_fail);
    }

    /**
     * 微信注册登录
     */
    public ServiceResult registLogin(String ip, String pushToken, String phone, String sms, String ticket) {
        JsonObject result = new JsonObject();
        Object hget = redisUtils.hget(CacheName.ticketToToken, ticket);
        ServiceResult smsResult = smsBiz.checkSmsCode(SmsTypeEnum.REGISTER.getCode(), phone, sms);
        if (!smsResult.status) {
            return smsResult;
        }
        ServiceResult chekResult = memberBiz.checkPhoneId(LoginType.sms.getCode(), phone, null);
        if (!chekResult.status) {
            MemberVo memberVo = memberBiz.getByPhone(phone);
            if (ObjectUtils.isEmpty(memberVo.getWxUnionid())) {
                if (!ObjectUtils.isEmpty(hget)) {
                    Member member = new Member();
                    member.setMemberId(memberVo.getMemberId());
                    member.setWxUnionid((String) hget);
                    memberService.update(member);
                }
            }
            //登录成功 TODO
            if (memberVo != null) {
                SimpleMemberVo sMemberVo = new SimpleMemberVo();
                BeanUtils.copyProperties(memberVo, sMemberVo);
                if (memberVo.getRegTime() != null) {
                    sMemberVo.setRegTime(memberVo.getRegTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                sMemberVo.setPhone(sMemberVo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                result.add("member", GsonUtils.fromJson(GsonUtils.toJson(sMemberVo), JsonObject.class));
                result.add("auth",buildToken(memberVo.getMemberId()));
            }
            result.addProperty("ticket", ticket);
            return buildOK(result);
        }
        Member member = new Member();

        member.setRegIp(ip);
        member.setPushToken(pushToken);
        member.setPhone(phone);
        member.setInviteesStatus(1);
        member.setAvatarUrl(cacheBiz.getSystemDict(Constants.default_headImg));
        member.setNickName("WN" + RandomUtils.getRandom(4) + phone.substring(phone.length() - 4));
        if (!ObjectUtils.isEmpty(hget)) {
            member.setWxUnionid((String) hget);
        }
        ServiceResult addResult = memberService.add(member);
        if (addResult.status) {
            SimpleMemberVo sMemberVo = new SimpleMemberVo();
            BeanUtils.copyProperties(member, sMemberVo);
            if (member.getRegTime() != null) {
                sMemberVo.setRegTime(member.getRegTime().toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
            sMemberVo.setPhone(sMemberVo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            result.add("member", GsonUtils.fromJson(GsonUtils.toJson(sMemberVo), JsonObject.class));
            result.add("auth",buildToken(member.getMemberId()));
            return buildOK(result);
        }
        return buildFail(false, ConstantsMsg.member_register_fail);
    }

    public Map<String, Object> inviterCount(Integer memberId) {
        Member member = new Member();
        member.setInviter(memberId);
        Map<String, Object> inviterCount = memberService.inviterCount(memberId);
        return inviterCount;
    }

    /**
     * 邀请记录
     */
    public PageInfo<MemberVo> inviterList(Integer memberId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<MemberVo> list = memberService.inviterList(memberId);
        //todo:对接蜗唱加票活动已结束
        /*if (list != null && list.size() > 4) {
            mqBiz.push(MqConstants.INVITE_ADD_TICKET_EXCHANGE, MqConstants.INVITE_ADD_TICKET_ROUTINGKEY, GsonUtils.toJson(list));
        }*/
        list.forEach(memberVo -> {
            memberVo.setPhone(memberVo.getPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
            Integer inviteesStatus = memberVo.getInviteesStatus();
            memberVo.setStatus(inviteesStatus == 0 ? "非邀请注册用户" : inviteesStatus == 1 ? "未邀请成功" : "邀请成功");
        });

        return new PageInfo<MemberVo>(list);
    }

    public PageInfo<MemberVo> adminInviterList(Integer pageNum, Integer pageSize, Integer memberId, Integer status) {
        PageHelper.startPage(pageNum, pageSize);
        Member member = new Member();
        member.setInviter(memberId);
        member.setInviteesStatus(status);
        List<MemberVo> list = memberService.list(member);
        list.forEach(memberVo -> {
            Integer inviteesStatus = memberVo.getInviteesStatus();
            memberVo.setStatus(inviteesStatus == 0 ? "非邀请注册用户" : inviteesStatus == 1 ? "未邀请成功" : "邀请成功");
        });
        return new PageInfo<MemberVo>(list);
    }

    public ServiceResult bindCa(Integer memberId, String smartCardCode) {
        MemberVo memberVo = memberBiz.info(memberId);
        if (!ObjectUtils.isEmpty(memberVo) && memberVo.getBindCa() == 0) {
            Member m = new Member();
            m.setSmartCardCode(smartCardCode);
            List<MemberVo> list = memberService.list(m);
            if (list.size() > 10) {
                return buildFail(ConstantsMsg.cps_bind_beyond);
            }
            Member member = new Member();
            member.setMemberId(memberId);
            member.setSmartCardCode(smartCardCode);
            member.setBindCa(1);
            ServiceResult updateResult = memberService.update(member);
            if (updateResult.getStatus()) {
                return buildOK(true, ConstantsMsg.cps_bind_success);
            }
        }
        return buildFail(ConstantsMsg.cps_bind_fail);
    }

    public ServiceResult export(String taskName, Integer task, String params) {
        JsonObject obj = GsonUtils.fromJson(params, JsonObject.class);
        Member member = new Member();
        if (!ObjectUtils.isEmpty(obj) && !ObjectUtils.isEmpty(obj.get("memberId"))) {
            Integer memberId = obj.get("memberId").getAsInt();
            member.setInviter(memberId);
            if (!ObjectUtils.isEmpty(obj.get("status"))) {
                Integer status = obj.get("status").getAsInt();
                member.setInviteesStatus(status);
            }
        }
        List<MemberVo> list = memberService.list(member);
        List<Map<String, Object>> inviterList = new LinkedList<Map<String, Object>>();
        if (!ObjectUtils.isEmpty(list)) {
            list.forEach(o -> {
                Map<String, Object> map = new ConcurrentHashMap<String, Object>();
                map.put("memberId", o.getMemberId());
                map.put("nickName", o.getNickName());
                map.put("phone", o.getPhone());
                map.put("adress", o.getProvince() + o.getCity());
                map.put("state", o.getInviteesStatus() == 1 ? "未邀请成功" : "邀请成功");
                inviterList.add(map);
            });
        }
        String[] rowsName = new String[]{"序号", "用户id", "用户昵称", "用户手机", "用户区域", "状态"};
        List<Object[]> dataList = new LinkedList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < inviterList.size(); i++) {
            Map<String, Object> m = inviterList.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i;
            objs[1] = m.get("memberId");
            objs[2] = m.get("nickName");
            objs[3] = m.get("phone");
            objs[4] = m.get("adress");
            objs[5] = m.get("state");
            dataList.add(objs);
        }
        JsonObject cosConf = GsonUtils.fromJson(cacheBiz.getSystemDict(Constants.tencent_cloud_cos_conf), JsonObject.class);
        ExportExcel ex = new ExportExcel(taskName, rowsName, dataList, task, path, cosConf);
        String link = ex.export();
        if (!ObjectUtils.isEmpty(link)) {
            return buildOK(link, "");
        }
        return buildFail(false, "");
    }

    /**
     * 通过用户昵称获取用户信息
     *
     * @param name
     * @return
     */
    public List<MemberVo> getMemberInfoByName(String name) {
        Member member = new Member();
        member.setNickName(name);
        return memberService.list(member);
    }

    /**
     * 通过手机号获取用户信息
     *
     * @param phone
     * @return
     */
    public MemberVo getMemberInfoByPhone(String phone) {
        Member member = new Member();
        member.setPhone(phone);
        return memberService.get(member);
    }

    /**
     * 通过会员id获取用户信息
     *
     * @param memberId
     * @return
     */
    public ServiceResult getMemberInfoByMemberId(Integer memberId) {
        Member member = new Member();
        member.setMemberId(memberId);
        MemberVo memberVo = memberService.get(member);
        if (memberVo == null) {
            buildFail(false, ConstantsMsg.getUserInfo_fail);
        }
        return buildOK(memberVo);
    }

    /**
     * 邀请记录列表
     */
    public List<MemberVo> getInviteRecordList(Integer memberId, String regTime, LocalDateTime startDateTime, LocalDateTime endDateTime) {
        return memberService.inviterListByRegTime(memberId, regTime,startDateTime,endDateTime);
    }

    /**
     * 邀请记录列表
     */
    public List<MemberVo> getInviteRecordList(Integer memberId, String regTime) {
        return getInviteRecordList(memberId, regTime, null, null);
    }

    /**
     * 校验用户是否绑定微信
     */
    public Object checkMemberBindWx(Integer memberId) {
        MemberVo info = info(memberId);
        if (info == null) {
            return false;
        }
        return StringUtils.isNotBlank(info.getWxOpenid());
    }

    /**
     * 校验用户是否是邀请注册登录
     */
    public boolean checkMemberInviteRegister(Integer memberId) {
        MemberVo info = info(memberId);
        //判断是邀请用户
        if (info != null && info.getInviteesStatus() != 0) {
            //非邀请用户判断该期间内是否邀请人
            SystemDictVo systemDictVo = systemDictBiz.getByKey(Constants.MEMBER_INVITE_RULE);
            MemberInviteRuleDto memberInviteRuleDto = GsonUtils.fromJson(systemDictVo.getDictValue(), MemberInviteRuleDto.class);
            return info.getRegTime().after(Timestamp.valueOf(memberInviteRuleDto.getRegTime()));
        }
        return false;
    }

    /**
     * 校验用户是否是邀请注册登录
     */
    public boolean checkMemberInvite(Integer memberId) {
        MemberVo info = info(memberId);
        //判断是邀请用户
        if (info != null && info.getInviteesStatus() != 0) {
            return true;
        }
        return false;
    }

    /**
     * 校验用户是否是邀请注册登录
     */
    public boolean checkMemberRegister(Integer memberId) {
        MemberVo info = info(memberId);
        if (info != null ) {
            //非邀请用户判断该期间内是否邀请人
            SystemDictVo systemDictVo = systemDictBiz.getByKey(Constants.MEMBER_INVITE_RULE);
            MemberInviteRuleDto memberInviteRuleDto = GsonUtils.fromJson(systemDictVo.getDictValue(), MemberInviteRuleDto.class);
            return info.getRegTime().after(Timestamp.valueOf(memberInviteRuleDto.getRegTime()));
        }
        return false;
    }


    public Integer getInviterByMemberId(Integer memberId) {
        return memberService.getInviterByMemberId(memberId);
    }

    public ServiceResult getMemberInfoByOpenId(String openId) {
        /*Member member = new Member();
        member.setWxOpenid(openId);
        MemberVo memberVo = memberService.get(member);*/
        Member member = new Member().selectOne(new QueryWrapper<Member>().eq(Member.WXOPENID, openId));
        if (member == null) {
            buildFail(false, ConstantsMsg.getUserInfo_fail);
        }
        return buildOK(member);
    }

    public ServiceResult bindWechat(String id, Integer memberId) {
        String wxUserInfoKey = MessageFormat.format(CacheKey.member_wxUserInfo, id);
        MemberVo member = memberService.getById(memberId);
        if (!ObjectUtils.isEmpty(id)) {
            JsonObject memberJson = new JsonObject();
            //授权
            ServiceResult tokenResult = wxBiz.getAccessToken(id);
            if (!tokenResult.getStatus()) {
                memberJson.addProperty("isBind", tokenResult.getStatus());
                return buildOK(memberJson, "");
            }
            JsonObject tokenJson = GsonUtils.fromJson(tokenResult.getData().toString(), JsonObject.class);
            String openid = tokenJson.get("openid").getAsString();
            //微信个人资料
            Member exist = new Member();
            exist.setWxOpenid(openid);
            MemberVo memberVo = memberService.get(exist);
            if (memberVo != null) {
                memberJson.addProperty("isBind", false);
                memberJson.addProperty("msg", "此微信已经绑定其他手机号");
                return buildOK(memberJson, "");
            }
            String accessToken = tokenJson.get("access_token").getAsString();
            ServiceResult userResult = wxBiz.getUserInfo(accessToken, openid);
            redisUtils.set(wxUserInfoKey, userResult.getData().toString(), 7200);
            if (!userResult.getStatus()) {
                memberJson.addProperty("isBind", userResult.getStatus());
                return buildOK(memberJson, "");
            }
            String phone = member.getPhone();
            if (!ObjectUtils.isEmpty(phone)) {
                //验证该手机号是否被绑定
                ServiceResult checkPhoneResult = memberBiz.checkPhoneId(LoginType.wechat.getCode(), phone, id);
                if (!checkPhoneResult.getStatus()) {
                    return checkPhoneResult;
                }
                //绑定/注册
                ServiceResult boundResult = memberBiz.boundPhone(LoginType.wechat.getCode(), id, phone);
                if (!boundResult.getStatus()) {
                    return boundResult;
                }
                memberJson.addProperty("isBind", true);
                return buildOK(memberJson, "");
            }
        }
        return buildFail(false, ConstantsMsg.bindPhone_fail);
    }

    /**
     * 邀请助力增加白金岛金币
     */
    @Transactional
    public ServiceResult inviterPlatinumIsland(String ip, String pushToken, String phone, String sms, Integer inviter) {
        MemberVo memberVo = this.info(inviter - 192008);

        if (memberVo != null && phone.equals(memberVo.getPhone())) {
            //提示语不同
            return buildOK(true, ConstantsMsg.member_invite_duplicate);
        }
        ServiceResult smsResult = smsBiz.checkSmsCode(SmsTypeEnum.INVIT.getCode(), phone, sms);
        if (!smsResult.status) {
            return smsResult;
        }
        MemberVo existMemberVo = memberBiz.getByPhone(phone);
        if (existMemberVo != null) {
            boolean result = checkRepeatInvitation(existMemberVo.getMemberId());
            if (result) {
                if (checkInviteCount(existMemberVo.getMemberId(), inviter - 192008)) {
                    return buildFail(false, ConstantsMsg.member_invite_fail_over);
                }
                recordTheSignInToBeAssisted(existMemberVo.getMemberId(), inviter - 192008);
                return buildOK(true, ConstantsMsg.member_invite_success);
            } else {
                return buildFail(false, ConstantsMsg.member_invite_fail_repeat);
            }
        } else {
            Member member = new Member();
            member.setRegIp(ip);
            member.setPushToken(pushToken);
            member.setPhone(phone);
            member.setInviter(inviter - 192008);
            member.setInviteesStatus(1);
            member.setAvatarUrl(cacheBiz.getSystemDict(Constants.default_headImg));
            member.setNickName("WN" + RandomUtils.getRandom(4) + phone.substring(phone.length() - 4));
            boolean insert = member.insert();
//            ServiceResult addResult = memberService.add(member);
            if (insert) {
                MemberTryWatchLiveRuleDto memberTryWatchRuleDto = JSONUtil.toBean(systemDictBiz.getStringByKey(MEMBER_TRY_WATCH_RULE), MemberTryWatchLiveRuleDto.class);
                if (memberTryWatchRuleDto != null) {
                    Boolean globalTryWatchSwitch = Boolean.valueOf(Optional.ofNullable(memberTryWatchRuleDto.getGlobalTryWatchSwitch()).orElse("false"));
                    if (globalTryWatchSwitch) {
                        mqBiz.push(MqConstants.MEMBER_TRY_WATCH_LIVE_EXCHANGE, MqConstants.MEMBER_TRY_WATCH_LIVE_ROUTINGKEY, GsonUtils.toJson(phone));
                    }
                }
                if (checkInviteCount(member.getMemberId(), inviter - 192008)) {
                    return buildFail(false, ConstantsMsg.member_invite_fail_over);
                }
                recordTheSignInToBeAssisted(member.getMemberId(), inviter - 192008);
                return buildOK(true, ConstantsMsg.member_invite_success);
            }
            return buildFail(false, ConstantsMsg.member_invite_fail);
        }
    }

    private boolean checkInviteCount(Integer memberId, Integer inviter) {
        List<MemberSigninRecord> memberSigninRecords = new MemberSigninRecord().selectList(new QueryWrapper<MemberSigninRecord>().eq(MemberSigninRecord.SIGN_TYPE, INVITER_PLATINUM_ISLAND_TYPE).eq(MemberSigninRecord.MEMBER_ID, memberId).eq(MemberSigninRecord.CREATE_BY, inviter));
        return memberSigninRecords.size() > 14;
    }

    private boolean checkRepeatInvitation(Integer memberId) {
        boolean result = false;
        try {
            MemberSigninRecord memberSigninRecord = new MemberSigninRecord().selectOne(new QueryWrapper<MemberSigninRecord>().eq(MemberSigninRecord.MEMBER_ID, memberId).eq(MemberSigninRecord.SIGN_TYPE, INVITER_PLATINUM_ISLAND_TYPE));
            result = memberSigninRecord == null;
        } catch (Exception e) {
            log.error(e.toString());
        }
        return result;
    }

    /**
     * 记录要协助的助力
     *
     * @param memberId
     * @param inviterId
     */
    private void recordTheSignInToBeAssisted(Integer memberId, Integer inviterId) {
        MemberSigninRecord memberSigninRecord = new MemberSigninRecord();
        memberSigninRecord.setSignType(INVITER_PLATINUM_ISLAND_TYPE);
        memberSigninRecord.setStatus(UN_LOGIN_STATUS);
        memberSigninRecord.setCreateTime(new Date());
        memberSigninRecord.setUpdateTime(new Date());
        memberSigninRecord.setMemberId(memberId);
        memberSigninRecord.setCreateBy(inviterId);
        memberSigninRecord.insert();
    }

    public ServiceResult bindTVAccount(String passport, Integer memberId) {
        MemberAccountRelated memberAccountRelated = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().eq(MemberAccountRelated.ACCOUNT_ID, passport).eq(MemberAccountRelated.STATUS, NORMAL_STATUS));
        if (memberAccountRelated != null) {
            MemberVo byId = Optional.ofNullable(memberService.getById(memberAccountRelated.getMemberId())).orElse(new MemberVo());
            return buildFail("该账号已和" + (byId.getPhone().length() > 10 ? StrUtil.hide(byId.getPhone(), 3, 7) : "") + "绑定过，请用该手机号登录领取金币哦~");
        }
        memberAccountRelated = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().eq(MemberAccountRelated.MEMBER_ID, memberId).eq(MemberAccountRelated.STATUS, NORMAL_STATUS));
        if (memberAccountRelated != null) {
            return buildFail("该用户已绑定其它设备");
        }
        memberAccountRelated = new MemberAccountRelated();
        memberAccountRelated.setMemberId(memberId);
        memberAccountRelated.setAccountId(passport);
        memberAccountRelated.setStatus(NORMAL_STATUS);
        memberAccountRelated.setCreateTime(new Date());
        memberAccountRelated.setUpdateTime(new Date());
        boolean insert = memberAccountRelated.insert();
        if (insert) {
            return buildOK(true, "绑定账号成功！请用该手机号登录领取金币哦~");
        }
        return buildFail("绑定账号失败！");
    }

    public ServiceResult getTVBindState(Integer memberId) {
        MemberAccountRelated memberAccountRelated = new MemberAccountRelated().selectOne(new QueryWrapper<MemberAccountRelated>().eq(MemberAccountRelated.MEMBER_ID, memberId).eq(MemberAccountRelated.STATUS, NORMAL_STATUS));
        return buildOK(memberAccountRelated != null);
    }

    public ServiceResult getMemberTotalPlatinumIsland(Integer memberId) {
        Map<String, Object> result = new HashMap<>();
        MemberAssetsDetail visitPlatinumIslandMemberAssets = Optional.ofNullable(new MemberAssetsDetail().selectOne(new QueryWrapper<MemberAssetsDetail>().eq(MemberAssetsDetail.MEMBER_ID, memberId).eq(MemberAssetsDetail.TYPE, VISIT_PLATINUM_ISLAND_MEMBER_ASSETS_TYPE))).orElse(new MemberAssetsDetail());

        List<MemberAssetsDetail> inviterPlatinumIslandMemberAssets = new MemberAssetsDetail().selectList(new QueryWrapper<MemberAssetsDetail>().eq(MemberAssetsDetail.MEMBER_ID, memberId).eq(MemberAssetsDetail.TYPE, INVITER_PLATINUM_ISLAND_MEMBER_ASSETS_TYPE));
        BigDecimal sum = Optional.ofNullable(inviterPlatinumIslandMemberAssets.stream().map(MemberAssetsDetail::getAmount).reduce(BigDecimal.ZERO, (bigDecimal, bigDecimal2) -> bigDecimal.add(bigDecimal2))).orElse(BigDecimal.ZERO);
        result.put("inviteTotalAmount", sum.intValue());
        result.put("visitTotalAmount", Optional.ofNullable(visitPlatinumIslandMemberAssets.getAmount()).orElse(BigDecimal.ZERO).intValue());
        result.put("totalAmount", sum.add(Optional.ofNullable(visitPlatinumIslandMemberAssets.getAmount()).orElse(BigDecimal.ZERO)).intValue());
        result.put("inviteCount", inviterPlatinumIslandMemberAssets.size());
        return buildOK(result);
    }

    public ServiceResult simpleExternalInfo(Integer memberId, String phone) {
        if (!ObjectUtils.isEmpty(memberId)) {
            MemberVo memberVo = memberService.getByPhone(phone);
            if (!ObjectUtils.isEmpty(memberVo)) {
                SimpleExtenalMemberVo simpleMemberVo = new SimpleExtenalMemberVo();
                BeanUtils.copyProperties(memberVo, simpleMemberVo);
                return buildOK(simpleMemberVo);
            }
        }
        return buildFail(ConstantsMsg.member_simpleInfo_fail);
    }
}
